package jp.sourceforge.akjrcp.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class URLDownloader {
	private FileOutputStream output;
	private YoutubeDLExecuter executer;

	private String youtubeDLPath;
	private String pythonPath;
	
	private boolean bestQuarity;
	public String getPythonPath() {
		return pythonPath;
	}

	public void setPythonPath(String pythonPath) {
		this.pythonPath = pythonPath;
	}



	public String getYoutubeDLPath() {
		return youtubeDLPath;
	}

	public void setYoutubeDLPath(String youtubeDLPath) {
		this.youtubeDLPath = youtubeDLPath;
	}

	public void cancel() throws IOException{
		if(output!=null){
			output.close();
		}
		if(executer!=null){
			executer.cancel();
		}
	}
	
	public void download(URL url,File exportFile) throws IOException{
		
		if(!exportFile.getParentFile().exists()){
			throw new IOException("directory not found:"+exportFile.getParentFile());
		}
		
		String urlText=url.toString();
		if(YoutubeUtils.isYoutubeVideoURL(urlText)){
			executer=new YoutubeDLExecuter();
			executer.setYoutubeDLPath(youtubeDLPath);
			executer.setPythonPath(pythonPath);
			//executer.setBestQuarity(bestQuarity); //now default is high quality mp4
			executer.setExportFile(exportFile);
			executer.execute(new URL[]{url});
			executer=null;
		}else{
			copyURLToFile(url,exportFile);
			output=null;//done;
		}
		
		
	}
	
	public  void copyURLToFile(URL source, File destination) throws IOException {
        InputStream input = source.openStream();
        try {
           output = openOutputStream(destination);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
    }
	

    public static FileOutputStream openOutputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && parent.exists() == false) {
                if (parent.mkdirs() == false) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file);
    }

	public boolean isBestQuarity() {
		return bestQuarity;
	}

	public void setBestQuarity(boolean bestQuarity) {
		this.bestQuarity = bestQuarity;
	}

}
